import React, { useEffect, useState } from "react";
import TicketItem from "./TicketItem";
import { useLoaderData, useSearchParams } from "react-router-dom";
import { getTrain } from "../../../api/info";
import { InfiniteScroll, PullToRefresh } from "antd-mobile";

function TrainList() {
  let [sp] = useSearchParams();
  let { list } = useLoaderData();
  const [page, setPage] = useState(1);
  let [trainList, setList] = useState(list);
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {
    setPage((prev) => prev + 1);
    const data = Object.fromEntries(sp);
    const data2 = { page: page + 1, ...data };
    console.log(data);

    const { data: res } = await getTrain(data2);
    setList((prev) => [...prev, ...res]);
    if (res.length === 0) {
      setHasMore(false);
    }
  }
  const onRefresh = async () => {
    const data = Object.fromEntries(sp);
    const { data: res } = await getTrain(data);
    setList(res);
    setPage(1);
    setHasMore(true);
  };
  useEffect(() => {
    window.scrollTo({ top: 0 });
    setList(list);
    setPage(1);
    setHasMore(true);
  }, [list]);
  return (
    <div style={{paddingTop:'45px'}}>
      <PullToRefresh onRefresh={onRefresh}>
        {trainList.map((item, i) => {
          return <TicketItem key={i} {...item}></TicketItem>;
        })}
      </PullToRefresh>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  );
}

export default TrainList;
